<?php
/**
 *
调用本类注入方法时，请传如下两个参数：
nns_task_id
nns_task_name
参数传值分三种情况：
categogy操作时：
nns_task_id  ： 分类名称
nns_task_name   ：sp分类id

c2_task操作（vod，index）：
nns_task_id  ： c2_task 的nns_id
nns_task_name   ：vod或者index名称

片源操作：（片源注入时都以分集为单位）
nns_task_id  ： 切片任务id
nns_task_name   ：分集名称
 *
 */
class c2_task_model{


	static $providerID = 'HNBB';
	static $providerType = 2;

	/**
	 *内地=1,港台=2,韩日=3,欧美=4, 东南亚=5，其他=99
	 */
	static $country_map = array(
		array('key'=>'香港','val'=>2),
		array('key'=>'中国','val'=>1),
		array('key'=>'台湾','val'=>2),
		array('key'=>'其他','val'=>99),
		array('key'=>'韩国','val'=>3),
		array('key'=>'美国','val'=>4),
		array('key'=>'法国','val'=>4),
		array('key'=>'英国','val'=>4),
		array('key'=>'日本','val'=>3),
		array('key'=>'内地','val'=>1),
		array('key'=>'德国','val'=>4),
	);

	/**
	 * 获取国家的映射
	 */

	static public function get_country($country){
		$result = 99;
		foreach(self::$country_map as $key=>$val){
			if($val['key']==$country){
				$result = $val['val'];
				break;
			}
		}
		return $result;
	}
	
	
	
	/**
	 * 新增
	 */
	
	static public function add_live($info){
		$action = "REGIST";
		$program_id = $info['nns_id'];
		$xml_str = '<adi:ADI2 xmlns="http://www.cablelabs.com/VODSchema/default" xmlns:adi="http://www.cablelabs.com/VODSchema/adi" xmlns:vod="http://www.cablelabs.com/VODSchema/vod">'.PHP_EOL;
		$c2_id = np_guid_rand();
		$xml_str .= self::do_live($info, $action, $c2_id);
		$xml_str .= '</adi:ADI2>'.PHP_EOL;
		$file_name = 'live_'.$program_id.'_'.$action.'.xml';
		$c2_info = array(
		'nns_id'=>$c2_id,
		'nns_task_type'=>'Channel',
		'nns_task_id'=> $info['nns_id'],
		'nns_task_name'=> $info['nns_name'],
		'nns_action'=>	$action,
		'nns_url' => $file_name,
		'nns_content' => $xml_str,
		'nns_desc' => 'Channel,'.$action,
		);
		
		return self::execute_c2($c2_info);
	}
	
	
	static public function update_live($info){
		$action = "UPDATE";
		$program_id = $info['nns_id'];
		$xml_str = '<adi:ADI2 xmlns="http://www.cablelabs.com/VODSchema/default" xmlns:adi="http://www.cablelabs.com/VODSchema/adi" xmlns:vod="http://www.cablelabs.com/VODSchema/vod">'.PHP_EOL;
		$c2_id = np_guid_rand();
		$xml_str .= self::do_live($info, $action, $c2_id);
		$xml_str .= '</adi:ADI2>'.PHP_EOL;
		$file_name = 'live_'.$program_id.'_'.$action.'.xml';
		$c2_info = array(
		'nns_id'=>$c2_id,
		'nns_task_type'=>'Channel',
		'nns_task_id'=> $info['nns_id'],
		'nns_task_name'=> $info['nns_name'],
		'nns_action'=>	$action,
		'nns_url' => $file_name,
		'nns_content' => $xml_str,
		'nns_desc' => 'Channel,'.$action,
		);
		
		return self::execute_c2($c2_info);
	}
	
	static public function delete_live($info){
		$action = "DELETE";
		$program_id = $info['nns_id'];
		$xml_str = '<adi:ADI2 xmlns="http://www.cablelabs.com/VODSchema/default" xmlns:adi="http://www.cablelabs.com/VODSchema/adi" xmlns:vod="http://www.cablelabs.com/VODSchema/vod">'.PHP_EOL;
		$c2_id = np_guid_rand();
		$xml_str .= self::do_live($info, $action, $c2_id);
		$xml_str .= '</adi:ADI2>'.PHP_EOL;
		$file_name = 'live_'.$program_id.'_'.$action.'.xml';
		$c2_info = array(
		'nns_id'=>$c2_id,
		'nns_task_type'=>'Channel',
		'nns_task_id'=> $info['nns_id'],
		'nns_task_name'=> $info['nns_name'],
		'nns_action'=>	$action,
		'nns_url' => $file_name,
		'nns_content' => $xml_str,
		'nns_desc' => 'Channel,'.$action,
		);
		
		return self::execute_c2($c2_info);
	}
	
	static public function do_live($info,$action,$c2_id){
		if($action=='REGIST'){
			$group_asset = 'OpenGroupAsset';
			$MetadataAsset = 'AddMetadataAsset';
			$ContentAsset = 'AcceptContentAsset';
		}elseif($action=='UPDATE'){
			$group_asset = 'ReplaceGroupAsset';
			$MetadataAsset = 'ReplaceMetadataAsset';
			$ContentAsset = 'ReplaceContentAsset';
		}elseif($action=='DELETE'){
			$group_asset = 'DropGroupAsset';
			$MetadataAsset = 'RemoveMetadataAsset';
			$ContentAsset = 'DestroyContentAsset';
		}
		$program_id = $info['nns_id'];
		
		$db = nn_get_db(NL_DB_READ);
		$sql = "select * from nns_live_ex where nns_live_id='{$info['nns_id']}' and nns_key='pid'";
		$live_ex_info = nl_db_get_one($sql, $db);
		//$c2_id = np_guid_rand();
		$xml_str = '';
		$xml_str .='<adi:'.$group_asset.' type="VODRelease" product="VOD">'.PHP_EOL;
		$xml_str .='<vod:VODRelease providerID="'.self::$providerID.'" providerType="'.self::$providerType.'" assetID="'.$program_id.'" updateNum="" groupAsset="Y" serialNo="'.$c2_id.'"></vod:VODRelease>'.PHP_EOL;
		$xml_str .='</adi:'.$group_asset.'>'.PHP_EOL;
		$xml_str .='<adi:'.$MetadataAsset.' groupProviderID="'.self::$providerID.'" groupAssetID="'.$program_id.'" type="Title" product="VOD">'.PHP_EOL;
		
		$xml_str .='<vod:Title providerID="'.self::$providerID.'" assetID="'.$program_id.'" updateNum="1">'.PHP_EOL;
		$xml_str .='<vod:ShowType>Channel</vod:ShowType>'.PHP_EOL;
		$xml_str .='<vod:TitleFull>'.$info['nns_name'].'</vod:TitleFull>'.PHP_EOL;
		if(is_array($live_ex_info)&&$live_ex_info!=null){			
			$xml_str .='<vod:CallSign>'.$live_ex_info['nns_value'].'</vod:CallSign>'.PHP_EOL;
		}		
		$xml_str .='</vod:Title>'.PHP_EOL;
		$xml_str .='</adi:'.$MetadataAsset.'>'.PHP_EOL;
		
		
		return $xml_str;
		//return self::execute_c2($c2_info);
	}

	
	
	static public function add_live_media($info){
		$action = "REGIST";
		$xml_str = '<adi:ADI2 xmlns="http://www.cablelabs.com/VODSchema/default" xmlns:adi="http://www.cablelabs.com/VODSchema/adi" xmlns:vod="http://www.cablelabs.com/VODSchema/vod">'.PHP_EOL;
		$c2_id = np_guid_rand();
		$xml_str .= self::do_live($info, 'UPDATE', $c2_id);
		$program_id = $info['nns_id'];
		
		$xml_str .= self::do_live_media($info, $action, $c2_id);
		
		$xml_str .= '</adi:ADI2>'.PHP_EOL;
		$file_name = 'live_media_'.$program_id.'_'.$action.'.xml';
		$c2_info = array(
		'nns_id'=>$c2_id,
		'nns_task_type'=>'PhysicalChannel',
		'nns_task_id'=> $info['nns_id'],
		'nns_task_name'=> $info['nns_name'].'-直播流',
		'nns_action'=>	$action,
		'nns_url' => $file_name,
		'nns_content' => $xml_str,
		'nns_desc' => 'PhysicalChannel,'.$action,
		);
		
		return self::execute_c2($c2_info);
	}
	
	
	static public function update_live_media($info){
		$action = "UPDATE";
		$xml_str = '<adi:ADI2 xmlns="http://www.cablelabs.com/VODSchema/default" xmlns:adi="http://www.cablelabs.com/VODSchema/adi" xmlns:vod="http://www.cablelabs.com/VODSchema/vod">'.PHP_EOL;
		$c2_id = np_guid_rand();
		$xml_str .= self::do_live($info, $action, $c2_id);
		$program_id = $info['nns_id'];
		
		$xml_str .= self::do_live_media($info, $action, $c2_id);
		
		$xml_str .= '</adi:ADI2>'.PHP_EOL;
		$file_name = 'live_media_'.$program_id.'_'.$action.'.xml';
		$c2_info = array(
		'nns_id'=>$c2_id,
		'nns_task_type'=>'PhysicalChannel',
		'nns_task_id'=> $info['nns_id'],
		'nns_task_name'=> $info['nns_name'].'-直播流',
		'nns_action'=>	$action,
		'nns_url' => $file_name,
		'nns_content' => $xml_str,
		'nns_desc' => 'PhysicalChannel,'.$action,
		);
		
		return self::execute_c2($c2_info);
	}
	
	static public function delete_live_media($info){
		$action = "DELETE";
		$xml_str = '<adi:ADI2 xmlns="http://www.cablelabs.com/VODSchema/default" xmlns:adi="http://www.cablelabs.com/VODSchema/adi" xmlns:vod="http://www.cablelabs.com/VODSchema/vod">'.PHP_EOL;
		$c2_id = np_guid_rand();
		$xml_str .= self::do_live($info, $action, $c2_id);
		$program_id = $info['nns_id'];
		
		$xml_str .= self::do_live_media($info, $action, $c2_id);
		
		$xml_str .= '</adi:ADI2>'.PHP_EOL;
		$file_name = 'live_media_'.$program_id.'_'.$action.'.xml';
		$c2_info = array(
		'nns_id'=>$c2_id,
		'nns_task_type'=>'PhysicalChannel',
		'nns_task_id'=> $info['nns_id'],
		'nns_task_name'=> $info['nns_name'].'-直播流',
		'nns_action'=>	$action,
		'nns_url' => $file_name,
		'nns_content' => $xml_str,
		'nns_desc' => 'PhysicalChannel,'.$action,
		);
		
		return self::execute_c2($c2_info);
	}
	
	static public function do_live_media($info,$action,$c2_id){
		$xml_str = '';
		if($action=='REGIST'){
			$group_asset = 'OpenGroupAsset';
			$MetadataAsset = 'AddMetadataAsset';
			$ContentAsset = 'AcceptContentAsset';
		}elseif($action=='UPDATE'){
			$group_asset = 'ReplaceGroupAsset';
			$MetadataAsset = 'ReplaceMetadataAsset';
			$ContentAsset = 'ReplaceContentAsset';
		}elseif($action=='DELETE'){
			$group_asset = 'DropGroupAsset';
			$MetadataAsset = 'RemoveMetadataAsset';
			$ContentAsset = 'DestroyContentAsset';
		}
		$program_id = $info['nns_id'].'_media';
		
		$db = nn_get_db(NL_DB_READ);
		$sql = "select * from nns_live_ex where nns_live_id='{$info['nns_id']}' and nns_key='pid'";
		$live_ex_info = nl_db_get_one($sql, $db);
		
		
		$xml_str .='<adi:'.$group_asset.' type="VODRelease" product="VOD">'.PHP_EOL;
		$xml_str .='<vod:VODRelease providerID="'.self::$providerID.'" providerType="'.self::$providerType.'" assetID="'.$program_id.'" updateNum="" groupAsset="Y" serialNo="'.$c2_id.'"></vod:VODRelease>'.PHP_EOL;
		$xml_str .='</adi:'.$group_asset.'>'.PHP_EOL;
		$xml_str .='<adi:'.$MetadataAsset.' groupProviderID="'.self::$providerID.'" groupAssetID="'.$program_id.'" type="Title" product="VOD" assetID="'.$program_id.'" updateNum="1" HDFlag="0">'.PHP_EOL;
		
		$xml_str .='<vod:Title providerID="'.self::$providerID.'" assetID="'.$program_id.'" updateNum="1">'.PHP_EOL;
		$xml_str .='<vod:ShowType>PhysicalChannel</vod:ShowType>'.PHP_EOL;
		$xml_str .='<vod:URL>http://172.25.0.5:80/nn_live.m3u8?id=CCTV1</vod:URL>'.PHP_EOL;
		$xml_str .='<vod:SrcType>1</vod:SrcType>'.PHP_EOL;
		$xml_str .='<vod:ServiceType>10</vod:ServiceType>'.PHP_EOL;
		$xml_str .='<vod:MimeType>45</vod:MimeType>'.PHP_EOL;
		$xml_str .='</vod:Title>'.PHP_EOL;
		$xml_str .='</adi:'.$MetadataAsset.'>'.PHP_EOL;
		$xml_str .= '<adi:AssociateContent type="Video" effectiveDate="" groupProviderID="'.self::$providerID.'" groupAssetID="'.$info['nns_id'].'" providerID="'.self::$providerID.'" assetID="'.$program_id.'"/>'.PHP_EOL;
		return $xml_str;
			
	}
	
	
	
	

	/**
	 * 添加内容栏目
	 */
	static public function add_categoy($category_info){
		$action = 'REGIST';
		return true;//self::do_category($category_info,$action);
	}
	/**
	 * 添加内容栏目
	 */
	static public function update_category($category_info){
		$action = 'UPDATE';
		return true;//self::do_category($category_info,$action);
	}
	static public function delete_category($param){
		return true;
	}


	/**
	 * @params array(
	 * nns_id
	 * nns_task_id
	 * )
	 */
	static public function delete_series($params){
		$action = "DELETE";
		$xml_str = '<?xml version="1.0" encoding="UTF-8"?><ADI xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" BizDomain="2" Priority="1">';
		$xml_str .= '<Objects>';
		$xml_str .= '<Object ElementType="Series" ID="' .$params['nns_id']. '" Action="' . $action . '" Code="' .$params['nns_id']. '">';

		$xml_str .= '</Object>';
		$xml_str .= '</Objects>';
		$xml_str .= '</ADI>';

		$file_name = 'series_'.$params['nns_id'].'_'.$action.'.xml';

		$c2_info = array(
		'nns_task_type'=>'Series',
		'nns_task_id'=>  isset($params['nns_task_id'])?$params['nns_task_id']:null,
		'nns_task_name'=>  isset($params['nns_task_name'])?$params['nns_task_name']:null,
		'nns_action'=>	$action,
		'nns_url' => $file_name,
		'nns_content' => $xml_str,
		'nns_desc' => 'Series,'.$action,
		);
		return self::execute_c2($c2_info);

	}
	//修改连续剧
	static public function update_series($vod_info){
		$action = 'UPDATE';
		return self::do_series($vod_info,$action);
	}
	//添加连续剧
	static public function add_series($vod_info){
		$action = 'REGIST';
		return self::do_series($vod_info,$action);
	}
	
	static public function build_series($vod_info,$action,$c2_id){
		$db = nn_get_db(NL_DB_READ);
		$vod_id = $vod_info['nns_id'];
        $program_id = $vod_id;
		if($action=='REGIST'){
			$group_asset = 'OpenGroupAsset';
			$MetadataAsset = 'AddMetadataAsset';
			$ContentAsset = 'AcceptContentAsset';
		}elseif($action=='UPDATE'){
			$group_asset = 'ReplaceGroupAsset';
			$MetadataAsset = 'ReplaceMetadataAsset';
			$ContentAsset = 'ReplaceContentAsset';
		}
		//$c2_id = np_guid_rand();
		$xml_str = '';
		$xml_str .='<adi:'.$group_asset.' type="VODRelease" product="VOD">'.PHP_EOL;
		$xml_str .='<vod:VODRelease providerID="'.self::$providerID.'" providerType="'.self::$providerType.'" assetID="'.$program_id.'" updateNum="" groupAsset="Y" serialNo="'.$c2_id.'"></vod:VODRelease>'.PHP_EOL;
		$xml_str .='</adi:'.$group_asset.'>'.PHP_EOL;
		$xml_str .='<adi:'.$MetadataAsset.' groupProviderID="'.self::$providerID.'" groupAssetID="'.$program_id.'" type="Title" product="VOD">'.PHP_EOL;
		$xml_str .='<vod:Title providerID="'.self::$providerID.'" assetID="'.$program_id.'" updateNum="1">'.PHP_EOL;
		$xml_str .='<vod:TitleFull><![CDATA['.$vod_info['nns_name'].']]></vod:TitleFull>'.PHP_EOL;//电视剧名称
		$xml_str .='<vod:ShowType>Series</vod:ShowType>'.PHP_EOL;//电视剧类型标识
		if($vod_info['nns_eng_name']){
		$xml_str .='<vod:EnglishName><![CDATA['.$vod_info['nns_eng_name'].']]></vod:EnglishName>'.PHP_EOL;//英文名称
		}
		if($vod_info['nns_summary']){
		$xml_str .='<vod:SummaryMedium><![CDATA['.$vod_info['nns_summary'].']]></vod:SummaryMedium>'.PHP_EOL;//中文描述
		$xml_str .='<vod:SummaryShort><![CDATA['.$vod_info['nns_summary'].']]></vod:SummaryShort>'.PHP_EOL;//看点
		}
		if(!empty($vod_info['nns_area'])){
			$country_code = self::get_country($vod_info['nns_area']);
			$xml_str .='<vod:CountryOfOrigin><![CDATA['.$country_code.']]></vod:CountryOfOrigin>'.PHP_EOL;//国家地区 内地=1,港台=2,韩日=3,欧美=4, 东南亚=5，其他=99
		}
		if(!empty($vod_info['nns_actor'])){
			$xml_str .='<vod:Actor type="Actor">'.PHP_EOL;//演员
			$xml_str .='<vod:LastNameFirst><![CDATA['.$vod_info['nns_actor'].']]></vod:LastNameFirst>'.PHP_EOL;
			$xml_str .='</vod:Actor>'.PHP_EOL;
		}
		//导演
		if(!empty($vod_info['nns_director'])){
			$xml_str .='<vod:Director><vod:LastNameFirst><![CDATA['.$vod_info['nns_director'].']]></vod:LastNameFirst></vod:Director>'.PHP_EOL;
		}
		//year
		if(!empty($vod_info['nns_show_time'])){
			$xml_str .= '<vod:Year><![CDATA['.date('Y',strtotime($vod_info['nns_show_time'])).']]></vod:Year>'.PHP_EOL;
		}
		//language
		if(!empty($vod_info['nns_language'])){
			$xml_str .= '<vod:Language><![CDATA['.$vod_info['nns_language'].']]></vod:Language>'.PHP_EOL;
		}
		//all_index
		if(!empty($vod_info['nns_all_index'])){
			$xml_str .='<vod:Items><![CDATA['.$vod_info['nns_all_index'].']]></vod:Items>'.PHP_EOL;
		}
		//nns_keyword
		if(!empty($vod_info['nns_keyword'])){
			$xml_str .='<vod:Keyword><![CDATA['.str_replace('/', ' ', $vod_info['nns_keyword']).']]></vod:Keyword>'.PHP_EOL;
		}
		//$xml_str .='<vod:IsAdvertise>0</vod:IsAdvertise>';//0：非广告内容; 1：广告内容

		$xml_str .='</vod:Title>'.PHP_EOL;
		$xml_str .= '</adi:'.$MetadataAsset.'>'.PHP_EOL;
		//category
		/*$xml_str .= '<adi:'.$MetadataAsset.' groupProviderID="'.self::$providerID.'" groupAssetID="'.$program_id.'" type="CategoryPath" product="VOD">'.PHP_EOL;
		$xml_str .= '<vod:CategoryPath providerID="'.self::$providerID.'" assetID="'.$program_id.'" updateNum="1">'.PHP_EOL;
		if(is_array($vod_info['nns_category_id'])){
			foreach ($vod_info['nns_category_id'] as  $category_id) {
				$sql = "select nns_name from nns_mgtvbk_category where nns_sp_category_id='$category_id' and nns_org_id='".SP_ORG_ID."'";
				$category_name = nl_db_get_col($sql, $db);
				$xml_str .= '<vod:Classification><![CDATA['.$category_name.']]></vod:Classification>'.PHP_EOL;
			}

		}
		$xml_str .='</vod:CategoryPath>';
		*/
		//$xml_str .= '</adi:'.$MetadataAsset.'>'.PHP_EOL;
		//images
		if(!empty($vod_info['nns_image2'])){
			$xml_str .= '<adi:'.$ContentAsset.' type="Image" metadataOnly="N">'.PHP_EOL;
			//图片的实体ID取用图片的名称 
			//$image_asset_id = str_replace('/', '', $vod_info['nns_image2']);
			$image_asset_id = $program_id.'image2';
			$file_fix = substr($vod_info['nns_image2'],  -3,3);
			$img_save_name = str_replace('.JPG','.jpg',$vod_info['nns_image2']);
			$pic_url = self::get_image_url($img_save_name);
			$xml_str .= '<vod:Image providerID="'.self::$providerID.'" assetID="'.$image_asset_id.'" updateNum="1" transferContentURL="'.$pic_url.'" imageEncodingProfile="'.$file_fix.'"    fileName="'.$image_asset_id.'">'.PHP_EOL;
			$xml_str .='<vod:FileType><![CDATA[3]]></vod:FileType>'.PHP_EOL;
			$xml_str .='<vod:Usage><![CDATA[15]]></vod:Usage>'.PHP_EOL;
			$xml_str .='</vod:Image>'.PHP_EOL;
			$xml_str .= '</adi:'.$ContentAsset.'>'.PHP_EOL;
			$xml_str .= '<adi:AssociateContent type="Image"  groupProviderID="'.self::$providerID.'" groupAssetID="'.$program_id.'" providerID="'.self::$providerID.'" assetID="'.$image_asset_id.'"/>'.PHP_EOL;
		}		
		return $xml_str;
	}
	
	//连续剧
	static public function do_series($vod_info,$action){
		$db = nn_get_db(NL_DB_READ);
		$vod_id = $vod_info['nns_id'];
        $program_id = $vod_id;
		
		$c2_id = np_guid_rand();
		$xml_str = '<adi:ADI2 xmlns="http://www.cablelabs.com/VODSchema/default" xmlns:adi="http://www.cablelabs.com/VODSchema/adi" xmlns:vod="http://www.cablelabs.com/VODSchema/vod">'.PHP_EOL;
			$xml_str_tmp = self::build_series($vod_info, $action, $c2_id);
		$xml_str .= $xml_str_tmp.'</adi:ADI2>'.PHP_EOL;
		$file_name = 'series_'.$vod_id.'_'.$action.'.xml';
		$c2_info = array(
		'nns_id'=>$c2_id,
		'nns_task_type'=>'Series',
		'nns_task_id'=> isset($vod_info['nns_task_id'])?$vod_info['nns_task_id']:null,
		'nns_task_name'=> isset($vod_info['nns_task_name'])?$vod_info['nns_task_name']:null,
		'nns_action'=>	$action,
		'nns_url' => $file_name,
		'nns_content' => $xml_str,
		'nns_desc' => 'Series,'.$action,
		);
		return self::execute_c2($c2_info);

	}




	static public function build_vod($vod_info,$action,$c2_id){
		$db = nn_get_db(NL_DB_READ);
		

		$vod_id = $vod_info['nns_id'];
        $program_id = $vod_id;
		if($action=='REGIST'){
			$group_asset = 'OpenGroupAsset';
			$MetadataAsset = 'AddMetadataAsset';
			$ContentAsset = 'AcceptContentAsset';
		}elseif($action=='UPDATE'){
			$group_asset = 'ReplaceGroupAsset';
			$MetadataAsset = 'ReplaceMetadataAsset';
			$ContentAsset = 'ReplaceContentAsset';
		}
		//$c2_id = np_guid_rand();
		//$xml_str = '<adi:ADI2 xmlns="http://www.cablelabs.com/VODSchema/default" xmlns:adi="http://www.cablelabs.com/VODSchema/adi" xmlns:vod="http://www.cablelabs.com/VODSchema/vod">';
		$xml_str = '';
		if($vod_info['nns_series_flag']==1){//连续剧	
		
			$xml_str .='<adi:'.$group_asset.' type="VODRelease" product="VOD">'.PHP_EOL;
			$xml_str .='<vod:VODRelease providerID="'.self::$providerID.'" providerType="'.self::$providerType.'" assetID="'.$program_id.'" updateNum="" groupAsset="Y" serialNo="'.$c2_id.'"></vod:VODRelease>'.PHP_EOL;
			$xml_str .='</adi:'.$group_asset.'>'.PHP_EOL;
			
			
			$xml_str .='<adi:'.$MetadataAsset.' groupProviderID="'.self::$providerID.'" groupAssetID="'.$program_id.'" type="Title" product="VOD">'.PHP_EOL;
			$xml_str .='<vod:Title providerID="'.self::$providerID.'" assetID="'.$program_id.'" updateNum="1"><vod:ShowType>Series</vod:ShowType>'.PHP_EOL;
			if($vod_info['nns_name']){
			$xml_str .='<vod:TitleFull><![CDATA['.$vod_info['nns_name'].']]></vod:TitleFull>'.PHP_EOL;
			}
			$xml_str .='<vod:TVIdentifier authority="CST" seriesID="'.$vod_info['nns_vod_id'].'"></vod:TVIdentifier>'.PHP_EOL;
			$xml_str .='<vod:RunTime><![CDATA['.$vod_info['nns_view_len'].']]></vod:RunTime>'.PHP_EOL;
			$xml_str .='<vod:EpisodeID><![CDATA['.intval($vod_info['nns_index']+1).']]></vod:EpisodeID>'.PHP_EOL;
			if($vod_info['nns_summary']){
			$xml_str .='<vod:SummaryMedium><![CDATA['.$vod_info['nns_summary'].']]></vod:SummaryMedium>'.PHP_EOL;
			}
			$xml_str .='<vod:IsAdvertise>0</vod:IsAdvertise>'.PHP_EOL;
			$xml_str .='</vod:Title>'.PHP_EOL;
			$xml_str .='</adi:'.$MetadataAsset.'>'.PHP_EOL;


			if(!empty($vod_info['nns_image2'])){
				$xml_str .= '<adi:'.$ContentAsset.' type="Image" metadataOnly="N">'.PHP_EOL;
				//图片的实体ID取用图片的名称
				//$image_asset_id = str_replace('/', '', $vod_info['nns_image2']);
				$image_asset_id = $program_id.'image2';
				$file_fix = substr($vod_info['nns_image2'],  -3,3);
				$img_save_name = str_replace('.JPG','.jpg',$vod_info['nns_image2']);
				$pic_url = self::get_image_url($img_save_name);
				$xml_str .= '<vod:Image providerID="'.self::$providerID.'" assetID="'.$image_asset_id.'" updateNum="1" transferContentURL="'.$pic_url.'" imageEncodingProfile="'.$file_fix.'"   fileName="'.$image_asset_id.'">'.PHP_EOL;
				$xml_str .='<vod:FileType><![CDATA[3]]></vod:FileType>'.PHP_EOL;
				$xml_str .='<vod:Usage><![CDATA[15]]></vod:Usage>'.PHP_EOL;
				$xml_str .='</vod:Image>'.PHP_EOL;
				$xml_str .= '</adi:'.$ContentAsset.'>'.PHP_EOL;
				$xml_str .= '<adi:AssociateContent type="Image"  groupProviderID="'.self::$providerID.'" groupAssetID="'.$program_id.'" providerID="'.self::$providerID.'" assetID="'.$image_asset_id.'"/>'.PHP_EOL;
			}
			$xml_str .='<adi:AssociateGroup  groupProviderID="'.self::$providerID.'" providerID="'.self::$providerID.'" assetID="'.$program_id.'" sourceGroupAssetID="'.$program_id.'" targetGroupAssetID="'.$vod_info['nns_vod_id'].'"/>'.PHP_EOL;
		}else{
			$xml_str .='<adi:'.$group_asset.' type="VODRelease" product="VOD">'.PHP_EOL;
			$xml_str .='<vod:VODRelease providerID="'.self::$providerID.'" providerType="'.self::$providerType.'" assetID="'.$program_id.'" updateNum="" groupAsset="Y" serialNo="'.$c2_id.'"></vod:VODRelease>'.PHP_EOL;
			$xml_str .='</adi:'.$group_asset.'>'.PHP_EOL;
			$xml_str .='<adi:'.$MetadataAsset.' groupProviderID="'.self::$providerID.'" groupAssetID="'.$program_id.'" type="Title" product="VOD">'.PHP_EOL;
			$xml_str .='<vod:Title providerID="'.self::$providerID.'" assetID="'.$program_id.'" updateNum="1">'.PHP_EOL;
			$xml_str .='<vod:TitleFull><![CDATA['.$vod_info['nns_name'].']]></vod:TitleFull>'.PHP_EOL;//名称
			$xml_str .='<vod:ShowType>Movie</vod:ShowType>'.PHP_EOL;//类型标识
			if($vod_info['nns_eng_name']){
			$xml_str .='<vod:EnglishName><![CDATA['.$vod_info['nns_eng_name'].']]></vod:EnglishName>'.PHP_EOL;//英文名称
			}
			if($vod_info['nns_summary']){
			$xml_str .='<vod:SummaryMedium><![CDATA['.$vod_info['nns_summary'].']]></vod:SummaryMedium>'.PHP_EOL;//中文描述
			$xml_str .='<vod:SummaryShort><![CDATA['.$vod_info['nns_summary'].']]></vod:SummaryShort>'.PHP_EOL;//看点
			}
			if(!empty($vod_info['nns_area'])){
				$country_code = self::get_country($vod_info['nns_area']);
				$xml_str .='<vod:CountryOfOrigin><![CDATA['.$country_code.']]></vod:CountryOfOrigin>'.PHP_EOL;//国家地区 内地=1,港台=2,韩日=3,欧美=4, 东南亚=5，其他=99
			}
			if(!empty($vod_info['nns_actor'])){
				$xml_str .='<vod:Actor type="Actor">'.PHP_EOL;//演员
				$xml_str .='<vod:LastNameFirst><![CDATA['.$vod_info['nns_actor'].']]></vod:LastNameFirst>'.PHP_EOL;
				$xml_str .='</vod:Actor>'.PHP_EOL;
			}
			//导演
			if(!empty($vod_info['nns_director'])){
				$xml_str .='<vod:Director><vod:LastNameFirst><![CDATA['.$vod_info['nns_director'].']]></vod:LastNameFirst></vod:Director>'.PHP_EOL;
			}
			//year
			if(!empty($vod_info['nns_show_time'])){
				$xml_str .= '<vod:Year><![CDATA['.date('Y',strtotime($vod_info['nns_show_time'])).']]></vod:Year>'.PHP_EOL;
			}
			//language
			if(!empty($vod_info['nns_language'])){
				$xml_str .= '<vod:Language><![CDATA['.$vod_info['nns_language'].']]></vod:Language>'.PHP_EOL;
			}
			//nns_keyword
			if(!empty($vod_info['nns_keyword'])){
				$xml_str .='<vod:Keyword><![CDATA['.str_replace('/', ' ', $vod_info['nns_keyword']).']]></vod:Keyword>'.PHP_EOL;
			}
			$xml_str .='</vod:Title>'.PHP_EOL;
			$xml_str .='</adi:'.$MetadataAsset.'>'.PHP_EOL;

			//category
			/*$xml_str .= '<adi:'.$MetadataAsset.' groupProviderID="'.self::$providerID.'" groupAssetID="'.$program_id.'" type="CategoryPath" product="VOD">';
			$xml_str .= '<vod:CategoryPath providerID="'.self::$providerID.'" assetID="'.$program_id.'" updateNum="1">'.PHP_EOL;
			if(is_array($vod_info['nns_category_id'])){
				foreach ($vod_info['nns_category_id'] as  $category_id) {
					$sql = "select nns_name from nns_mgtvbk_category where nns_sp_category_id='$category_id' and nns_org_id='".SP_ORG_ID."'";
					$category_name = nl_db_get_col($sql, $db);
					$xml_str .= '<vod:Classification><![CDATA['.$category_name.']]></vod:Classification>'.PHP_EOL;
				}
			}
			$xml_str .= '</vod:CategoryPath>';*/
			//$xml_str .= '</adi:'.$MetadataAsset.'>'.PHP_EOL;
			//images
			if(!empty($vod_info['nns_image2'])){
				$xml_str .= '<adi:'.$ContentAsset.' type="Image" metadataOnly="N">'.PHP_EOL;
				//图片的实体ID取用图片的名称
				//$image_asset_id = str_replace('/', '', $vod_info['nns_image2']);
				$image_asset_id = $program_id.'image2';
				$file_fix = substr($vod_info['nns_image2'],  -3,3);
				$img_save_name = str_replace('.JPG','.jpg',$vod_info['nns_image2']);
				$pic_url = self::get_image_url($img_save_name);
				$xml_str .= '<vod:Image providerID="'.self::$providerID.'" assetID="'.$image_asset_id.'" updateNum="1" transferContentURL="'.$pic_url.'" imageEncodingProfile="'.$file_fix.'"    fileName="'.$image_asset_id.'">'.PHP_EOL;
				$xml_str .='<vod:FileType><![CDATA[3]]></vod:FileType>'.PHP_EOL;
				$xml_str .='<vod:Usage><![CDATA[15]]></vod:Usage>'.PHP_EOL;
				$xml_str .='</vod:Image>'.PHP_EOL;
				$xml_str .= '</adi:'.$ContentAsset.'>'.PHP_EOL;
				$xml_str .= '<adi:AssociateContent type="Image"  groupProviderID="'.self::$providerID.'" groupAssetID="'.$program_id.'" providerID="'.self::$providerID.'" assetID="'.$image_asset_id.'"/>'.PHP_EOL;
			}
		}
		$xml_str .= '';
		
		return $xml_str;
	}

	/**
	 * 点播内容/点播分集
	 * $vod_info array(
	 * 'nns_id'   影片id/分集id
	 * 'nns_vod_id' 分集属于影片id
	 * 'nns_category_id'  影片的栏目id
	 * 'nns_series_flag' 连续剧分集标识
	 * )
	 * 目前实现上，给对方的影片id都是我方的分集id，因为片源是和分集关联的；
	 * 所以在删除影片时，也是用分集id删除
	 */
	static public function do_vod($vod_info,$action){
		$db = nn_get_db(NL_DB_READ);
		$db_w = nn_get_db(NL_DB_WRITE);

		$vod_id = $vod_info['nns_id'];
        $program_id = $vod_id;
		if($action=='REGIST'){
			$group_asset = 'OpenGroupAsset';
			$MetadataAsset = 'AddMetadataAsset';
			$ContentAsset = 'AcceptContentAsset';
		}elseif($action=='UPDATE'){
			$group_asset = 'ReplaceGroupAsset';
			$MetadataAsset = 'ReplaceMetadataAsset';
			$ContentAsset = 'ReplaceContentAsset';
		}
		$c2_id = np_guid_rand();
		$xml_str = '<adi:ADI2 xmlns="http://www.cablelabs.com/VODSchema/default" xmlns:adi="http://www.cablelabs.com/VODSchema/adi" xmlns:vod="http://www.cablelabs.com/VODSchema/vod">'.PHP_EOL;
		
		
		if($vod_info['nns_series_flag']==1){//连续剧				
			//$vod_info['nns_vod_id']			
			$sql="select * from nns_mgtvbk_c2_task where nns_type='vod' and nns_org_id='sihua' and nns_ref_id='{$vod_info['nns_vod_id']}'";
			$info = nl_db_get_one($sql, $db);
			if(is_array($info)&&$info!=null){
				$series_info =  content_task_model::vod($info['nns_id'],null,true);
				
				if(is_array($series_info)){
					//$new_c2_id = np_guid_rand();
					$series_xml = self::build_series($series_info, 'UPDATE', $c2_id);
					$xml_str .= $series_xml;
				}else{
					$sql = "select * from nns_mgtvbk_c2_task where nns_type='index' and and nns_org_id='sihua' and nns_id='{$vod_info['nns_task_id']}'";
					$info_2 = nl_db_get_one($sql, $db);
					if(is_array($info_2)&&$info_2!=null){
						if($info_2['nns_action']=='add'){
							$sql = "update nns_mgtvbk_c2_task set nns_status=1 where nns_id='{$info_2['nns_id']}'";
							nl_execute_by_db($sql, $db_w);
						}elseif($info_2['nns_action']=='modify'){
							$sql = "update nns_mgtvbk_c2_task set nns_status=2 where nns_id='{$info_2['nns_id']}'";
							nl_execute_by_db($sql, $db_w);
						}elseif($info_2['nns_action']=='destroy'){
							$sql = "update nns_mgtvbk_c2_task set nns_status=3 where nns_id='{$info_2['nns_id']}'";
							nl_execute_by_db($sql, $db_w);
						}
					}
					return ;
				}				
			}			
		}
		
		$xml_str_tmp = self::build_vod($vod_info, $action, $c2_id);		
		$xml_str .= $xml_str_tmp.'</adi:ADI2>';	
		
		//header("Content-Type:text/xml;charset=utf-8");
		//print_r($xml_str);die;
		//print_r($vod_info);die;
		$program_id = $vod_info['nns_id'];//vod nns_vod_id index nns_vod_index_id



		$file_name = 'program_'.$vod_info['nns_series_flag'].'_'.$program_id.'_'.$action.'.xml';
		//self::execute_c2($file_name, $xml_str);

		$c2_info = array(
		'nns_id' => $c2_id,
		'nns_task_type'=>'Program',
		'nns_task_id'=> isset($vod_info['nns_task_id'])?$vod_info['nns_task_id']:null,
		'nns_task_name'=> isset($vod_info['nns_task_name'])?$vod_info['nns_task_name']:null,
		'nns_action'=>	$action,
		'nns_url' => $file_name,
		'nns_content' => $xml_str,
		//'nns_result' =>  '['.$result['ret'].']'.$result['desc'],
		'nns_desc' => 'Program,'.$action,
		);
		return self::execute_c2($c2_info);
	}
	static public function get_image_url($img_path){
		if(defined('HW_DOANLOAD_IMG_METHOD') && HW_DOANLOAD_IMG_METHOD=='ftp'){
			$img_url = HW_DOANLOAD_IMG_FTP.$img_path;
		}else{
			$img_url = nl_image::epg_video_image_url($img_path);
		}
		return $img_url;
	}
	//修改点播
	static public function update_vod($vod_info){
		$action = 'UPDATE';
		return self::do_vod($vod_info,$action);
	}
	//添加点播
	static public function add_vod($vod_info){
		$action = 'REGIST';
		return self::do_vod($vod_info,$action);
	}
	/**
	 * params
	 */
	static public function delete_vod($params){
		$action = 'DELETE';

		$db = nn_get_db(NL_DB_READ);
		//删除媒体
		$sql = "select * from nns_vod_index where nns_id='".$params['nns_id']."'";
		$index_item = nl_db_get_one($sql,$db);
		if($index_item){

			$sql = "select nns_id from nns_vod_media where nns_vod_index_id='".$index_item['nns_id']."'";
			$vod_medias = nl_db_get_all($sql,$db);
			//删除媒体
			$media_ids = array();
			foreach($vod_medias as $item){
				$media_ids[] = $item['nns_id'];
			}
			c2_task_model::delete_movies(array('nns_ids'=>$media_ids,'nns_task_id'=>$index_item['nns_id'],'nns_task_name'=>$index_item['nns_name']));
		}

		$program_id = $params['nns_id'];
		//self::do_vod($vod_info,$action);
		$xml_str = '<?xml version="1.0" encoding="UTF-8"?>';
		$xml_str .='<program></program>';//自己根据sihua文档拼xml信息
		$file_name = 'program_'.$program_id.'_'.$action.'.xml';
		
		$c2_info = array(
		'nns_task_type'=>'Program',
		'nns_task_id'=> isset($params['nns_task_id'])?$params['nns_task_id']:null,
		'nns_task_name'=> isset($params['nns_task_name'])?$params['nns_task_name']:null,
		'nns_action'=>	$action,
		'nns_url' => $file_name,
		'nns_content' => $xml_str,
		'nns_desc' => 'Program,'.$action,
		);
		return self::execute_c2($c2_info);

	}

	/**
	 * 注入片源（以分集为单位,切片完成后调用）
	 * $index_media array(
	 * 'nns_video_id'
	 * 'nns_video_index_id'
	 * 'nns_task_id'
	 * 'nns_new_dir'
	 * 'nns_media_ids'
	 * )
	 */
	static public function add_movies_by_vod_index($index_media){
		
		
	
		DEBUG && i_write_log('--注入片源--');
		$db = nn_get_db(NL_DB_READ);	
		
		//$db->open();
		//先注入vod及index;否则，注入的片源将没有绑定任何影片
		
		$sql = "select * from nns_mgtvbk_c2_task " .
				"where nns_ref_id='".$index_media['nns_video_index_id']."'" .
						" and nns_org_id='".SP_ORG_ID."'" .
						" and  nns_type='index' and (nns_status>0 or nns_status=-1) limit 1";//没有注入或者注入失败,则先注入
		$result = nl_db_get_one($sql,$db);
		if($result){
			if($result['nns_action']=='destroy'){//如果该分集为删除，则不再注入该分集的片源
			    i_write_log('--该分集为删除，则不再注入该分集的片源--');
				return;
			}else{
				DEBUG && i_write_log('--注入片源时，先注入影片内容--');
				include_once dirname(__FILE__).'/content_task_model.php';
				content_task_model::vod($result['nns_id']);
			}
		}

		$sql = "select * from nns_vod_index where nns_id='".$index_media['nns_video_index_id']."'";
		$nns_vod_index_array =  nl_db_get_one($sql,$db);
		$nns_task_name= $nns_vod_index_array['nns_name'];

		$sql = "select nns_pinyin,nns_all_index from nns_vod where nns_id='".$index_media['nns_video_id']."'";
		$nns_vod_array = nl_db_get_one($sql,$db);
		$pinyin = $nns_vod_array['nns_pinyin'];
		
		$action = $index_media['action'];		
		
		$sql = "select * from nns_vod_media where  nns_vod_id='{$index_media['nns_video_id']}' and nns_vod_index_id='{$index_media['nns_video_index_id']}'  and nns_id='{$index_media['nns_media_id']}'   order by nns_kbps desc limit 1";
		$medias = nl_db_get_all($sql,$db);
		$kbps = $medias[0]['nns_kbps'];
		
		$nns_deleted = $medias[0]['nns_deleted'];
		if($nns_deleted==1){
			$action = 'DELETE';
		}
		
		/*　AcceptContentAsset,
　DestroyContentAsset,
ReplaceContentAsset*/
		
		if($action=='REGIST'){
			$ContentAsset = 'AcceptContentAsset';
		}elseif($action=='UPDATE'){
			$ContentAsset = 'ReplaceContentAsset';
		}elseif($action=='DELETE'){
			$ContentAsset = 'DestroyContentAsset';
		}
		
		
		
		
		
		
		
		//if($medias == false ) return false;
		if(is_array($medias) && count($medias)>0){
			$c2_id = np_guid_rand();
			//住信息按照修改处理			
			$xml_str = '<adi:ADI2 xmlns="http://www.cablelabs.com/VODSchema/default" xmlns:adi="http://www.cablelabs.com/VODSchema/adi" xmlns:vod="http://www.cablelabs.com/VODSchema/vod">'.PHP_EOL;
			
			//$sql="select * from nns_mgtvbk_c2_task where nns_";
			
			if($nns_vod_array['nns_all_index']>1){//连续剧
				$sql="select * from nns_mgtvbk_c2_task where nns_type='vod' and nns_org_id='sihua' and nns_ref_id='{$index_media['nns_video_id']}'";
				$info = nl_db_get_one($sql, $db);
				
				if(is_array($info)&&$info!=null){
					$series_info =  content_task_model::vod($info['nns_id'],null,true);
					if(is_array($series_info)){
						$new_c2_id = np_guid_rand();
						$series_xml = self::build_series($series_info, 'REGIST', $c2_id);
						$xml_str .= $series_xml;
					}else{
						$sql = "select * from nns_mgtvbk_c2_task where nns_type='media' and and nns_org_id='sihua' and nns_id='{$index_media['nns_id']}'";
						$info_2 = nl_db_get_one($sql, $db);
						if(is_array($info_2)&&$info_2!=null){
							if($info_2['nns_action']=='add'){
								$sql = "update nns_mgtvbk_c2_task set nns_status=1 where nns_id='{$info_2['nns_id']}'";
								nl_execute_by_db($sql, $db_w);
							}elseif($info_2['nns_action']=='modify'){
								$sql = "update nns_mgtvbk_c2_task set nns_status=2 where nns_id='{$info_2['nns_id']}'";
								nl_execute_by_db($sql, $db_w);
							}elseif($info_2['nns_action']=='destroy'){
								$sql = "update nns_mgtvbk_c2_task set nns_status=3 where nns_id='{$info_2['nns_id']}'";
								nl_execute_by_db($sql, $db_w);
							}
						}
						return ;
					}				
				}
			}

				
			
				$sql="select * from nns_mgtvbk_c2_task where nns_type='index' and nns_org_id='sihua' and nns_src_id='{$index_media['nns_video_id']}'  and  nns_ref_id='{$index_media['nns_video_index_id']}'";
				$info_1 = nl_db_get_one($sql, $db);	
				
				if(is_array($info_1)&&$info_1!=null){
					$series_info2 =  content_task_model::vod($info_1['nns_id'],null,true);
					if(is_array($series_info2)){
						$new_c3_id = np_guid_rand();
						$vod_xml = self::build_vod($series_info2, 'REGIST', $c2_id);
						$xml_str .= $vod_xml;
					}else{
						$sql = "select * from nns_mgtvbk_c2_task where nns_type='media' and and nns_org_id='sihua' and nns_id='{$index_media['nns_id']}'";
						$info_3 = nl_db_get_one($sql, $db);
						if(is_array($info_3)&&$info_3!=null){
							if($info_3['nns_action']=='add'){
								$sql = "update nns_mgtvbk_c2_task set nns_status=1 where nns_id='{$info_3['nns_id']}'";
								nl_execute_by_db($sql, $db_w);
							}elseif($info_3['nns_action']=='modify'){
								$sql = "update nns_mgtvbk_c2_task set nns_status=2 where nns_id='{$info_3['nns_id']}'";
								nl_execute_by_db($sql, $db_w);
							}elseif($info_3['nns_action']=='destroy'){
								$sql = "update nns_mgtvbk_c2_task set nns_status=3 where nns_id='{$info_3['nns_id']}'";
								nl_execute_by_db($sql, $db_w);
							}
						}
						return ;
					}				
				}	
			
			
			
			//$xml_str .= '<adi:OpenGroupAsset type="VODRelease" product="VOD"><vod:VODRelease providerID="'.self::$providerID.'" providerType="'.self::$providerType.'" assetID="'.$index_media['nns_video_index_id'].'" updateNum="" groupAsset="Y" serialNo="'.$c2_id.'"></vod:VODRelease></adi:OpenGroupAsset>';
			
			
			
			
			
			
			
			

			$media = array();
			$media_arr = array();

			$media_url = "";
			foreach($medias as $media_item){
                $mode = strtolower($media_item['nns_mode']);
                $media_arr[$mode] = $media_item;

			}
			if(!empty($media_arr['hd'])){
				$media = $media_arr['hd'];
			}else if(!empty($media_arr['std'])){
				$media = $media_arr['std'];
			}else if(!empty($media_arr['low'])){
				$media = $media_arr['low'];
			}
			if(empty($media)) return false;



			//foreach($medias as $media){
				//$url = 'ftp://username:password@ip:port/'.$index_media['nns_vod_index_id'].'/'.$media['nns_id'].'.m3u8';

				//$kbps_index = clip_task_model::get_kbps_index($media['nns_mode']);
                $video_profile =1;
                $mode = strtolower($media['nns_mode']);
                switch($mode){
                	case 'std':
                	$video_profile = 1;
                	break;
                	case 'hd':
                	$video_profile = 5;
                	break;
                	case 'low':
                	$video_profile = 3;
                	break;
                }

				// if($index_media['clip']===true){
					// if($pinyin){
						// if($index_media['nns_new_dir']){
							$url = MOVIE_FTP.$index_media['nns_date'].'/'.$index_media['nns_task_id'].'/'.$index_media['nns_media_id'].'.ts';
						// }else{
							// $url = MOVIE_FTP.$index_media['nns_date'].'/'.$media['nns_vod_index_id'].'/'.$index_media['nns_media_id'].'.ts';
						// }
					// }else{
						// if($index_media['nns_new_dir']){
							// $url = MOVIE_FTP.$index_media['nns_date'].'/'.$index_media['nns_task_id'].'/index.m3u8';
						// }else{
							// $url = MOVIE_FTP.$index_media['nns_date'].'/'.$media['nns_vod_index_id'].'/index.m3u8';
						// }
					// }
				// }else{
					// //TODO
					// $url = MOVIE_FTP.$media['nns_url'];
				// }
				//$url='ftp://ftp_star:hntv6yhn@221.181.100.156:52101//intertv/20140110/52cfbd1b10d9b4db8fdc7905581ee2e6/7f6763fed5a47d690f443edcc2e6a1a5.ts';
				//$nns_task_name = str_replace(" ", "", $nns_task_name);
				
				$url_ini="ftp://ftp_m3u8:ftp_m3u8@221.181.100.156:52103//".$index_media['nns_date'].'/'.$index_media['nns_task_id'].'/'.$index_media['nns_media_id'].'.ini';
				
				$url_arr = parse_url($url_ini);
				$notify_save_path = dirname(dirname(dirname(dirname(__FILE__)))).'/data/mgtv/ini/notify'.$url_arr["path"];
				
				if(!file_exists($notify_save_path)){
					$port = isset($url_arr["port"])?$url_arr["port"]:21;
					include_once NPDIR . '/np_ftp.php';
					$ftp1=new nns_ftp($url_arr['host'],$url_arr["user"],$url_arr["pass"],$port);
					$ftpcon1=$ftp1->connect();
            		if (empty($ftpcon1)) {
                		$ini_file =  array('size'=>'','md5'=>'');
				//return FALSE;
            		}
            		$path_parts = pathinfo($notify_save_path);
             		if (!is_dir($path_parts['dirname'])){
                	 	mkdir($path_parts['dirname'], 0777, true);
             		}
            		$rs = $ftp1->get(ltrim($url_arr["path"],'/'),$notify_save_path);
					if($rs==false){
                		$ini_file =  array('size'=>'','md5'=>'');
						//return false;
					}
				}
				$ini_file = parse_ini_file($notify_save_path);
				
				
				
			//
				
				
				$xml_str .= '<adi:'.$ContentAsset.' type="Video" metadataOnly="N" fileName="'.$nns_task_name.'" fileSize="'.$ini_file['size'].'" mD5CheckSum="'.$ini_file['md5'].'">'.PHP_EOL;
				//if($action!='DELETE'){
				$xml_str .= '<vod:Video providerID="'.self::$providerID.'" assetID="'.$index_media['nns_media_id'].'" updateNum="1" fileName="'.$nns_task_name.'"  transferContentURL="'.$url.'" encodingProfile="application/octet-stream">'.PHP_EOL;
				$xml_str .= '<vod:Duration>
<![CDATA['.$nns_vod_index_array['nns_time_len'].']]>
</vod:Duration>
<vod:Bitrate>
<![CDATA['.intval($kbps*1000).']]>
</vod:Bitrate>
<vod:FrameRate>
<![CDATA[5]]>
</vod:FrameRate>
<vod:FileType>
<![CDATA[1]]>
</vod:FileType>
<vod:Usage>
<![CDATA[1]]>
</vod:Usage>
<vod:ServiceType>
<![CDATA[1]]>
</vod:ServiceType>
<vod:MimeType>
<![CDATA[46]]>
</vod:MimeType>
<vod:HDFlag>0</vod:HDFlag></vod:Video>';
				//}

				$xml_str .= '</adi:'.$ContentAsset.'>'.PHP_EOL;
				//if($action!='DELETE'){
				$xml_str .= '<adi:AssociateContent type="Video" effectiveDate="" groupProviderID="'.self::$providerID.'" groupAssetID="'.$index_media['nns_video_index_id'].'" providerID="'.self::$providerID.'" assetID="'.$index_media['nns_media_id'].'"/>'.PHP_EOL;
				//}
				$xml_str .= '</adi:ADI2>'.PHP_EOL;

			$file_name = 'vod_media_'.$index_media['nns_video_index_id'].'_'.$index_media['nns_media_id'].'_'.$action.'.xml';

			$task_re_name = isset($index_media['nns_task_name'])?$index_media['nns_task_name']:$nns_task_name;
			$c2_info = array(
			'nns_id' => $c2_id,
			'nns_task_type'=>'Movie',
			'nns_task_id'=> isset($index_media['nns_id'])?$index_media['nns_id']:$index_media['nns_task_id'],
			'nns_task_name'=> $task_re_name.'_'.$mode,
			'nns_action'=>	$action,
			'nns_url' => $file_name,
			'nns_content' => $xml_str,
			//'nns_result' =>  '['.$result['ret'].']'.$result['desc'],
			'nns_desc' => 'Movie,'.$action,
			);
			return self::execute_c2($c2_info);

		}else{
			DEBUG && i_write_log('--没有片源--');
		}

	}


	/**
	 * 删除影片
	 * params array(
	 * nns_id,
	 * nns_task_id
	 * )
	 */
	static public function delete_movie($params){
		$action = 'DELETE';
		//
		//return self::do_movie($media,$action);
		$xml_str = '<?xml version="1.0" encoding="UTF-8"?><ADI xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" BizDomain="2" Priority="1">';
		$xml_str .= '<Objects>';
		$xml_str .= '<Object ElementType="Movie" ID="' .$params['nns_id']. '" Action="' . $action . '" Code="' .$params['nns_id']. '">';
		$xml_str .= '</Object>';
		$xml_str .= '</Objects>';
		$xml_str .= '</ADI>';
		//
		$file_name = 'movie_'.$params['nns_id'].'_'.$action.'.xml';
		//

		$c2_info = array(
		//'nns_id' => $c2_info['c2_id'],
		'nns_task_type'=>'Movie',
		'nns_task_id'=> isset($params['nns_task_id'])?$params['nns_task_id']:null,
		'nns_task_name'=> isset($params['nns_task_name'])?$params['nns_task_name']:null,
		'nns_action'=>	$action,
		'nns_url' => $file_name,
		'nns_content' => $xml_str,
		//'nns_result' =>  '['.$result['ret'].']'.$result['desc'],
		'nns_desc' => 'Movie,'.$action,
		);
		return self::execute_c2($c2_info);

	}
	/**
	 * 使用本方法时，请以分集为单位
	 * $params array(
	 * nns_ids
	 * )
	 */
	static public function delete_movies($params){
		$action = 'DELETE';
		//
		//return self::do_movie($media,$action);
		$xml_str = '<?xml version="1.0" encoding="UTF-8"?><ADI xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" BizDomain="2" Priority="1">';
		$xml_str .= '<Objects>';
		if(empty($params['nns_ids'] )) return ;
		foreach($params['nns_ids']  as $nns_id)	{
			$xml_str .= '<Object ElementType="Movie" ID="' .$nns_id. '" Action="' . $action . '" Code="' .$nns_id. '">';
			$xml_str .= '</Object>';
		}

		$xml_str .= '</Objects>';
		$xml_str .= '</ADI>';

		$guid =  np_guid_rand();
		//
		$file_name = 'movies_'.$guid.'_'.$action.'.xml';
		//

		$c2_info = array(
		//'nns_id' => $c2_info['c2_id'],
		'nns_task_type'=>'Movie',
		'nns_task_id'=>  isset($params['nns_task_id'])?$params['nns_task_id']:null,
		'nns_task_name'=>  isset($params['nns_task_name'])?$params['nns_task_name']:null,
		'nns_action'=>	$action,
		'nns_url' => $file_name,
		'nns_content' => $xml_str,
		//'nns_result' =>  '['.$result['ret'].']'.$result['desc'],
		'nns_desc' => 'Movie,'.$action,
		);
		return self::execute_c2($c2_info);

	}

	/**
	 * 华为没有处理的指令，再次重发
	 */
	static public function resend_c2_again(){
		$db = nn_get_db(NL_DB_READ);
		/************超时没返回重发************/
		$time_out = 3600;
		$sql = "select * from nns_mgtvbk_c2_log where nns_org_id='sihua' and nns_create_time < NOW() - INTERVAL ".$time_out." SECOND  and nns_notify_result is null  order by nns_create_time asc  limit 30";
		$all = nl_db_get_all($sql,$db);
		if(is_array($all)) {
			foreach($all as $item0){
				self::execute_c2_again($item0['nns_id']);
			}
		}

		/************以下为失败重发************/
		//连续剧
		$sql = "select * from nns_mgtvbk_c2_log where nns_org_id='sihua' and   nns_task_type='Series' and (nns_notify_result='-1' and (nns_notify_result_url='' or nns_notify_content like '%Download picture failed%' or nns_notify_content like '%Entity queue is full%') or nns_result like '%[-1]soap info is full%') and nns_again>=0 order by nns_again asc,nns_create_time asc  limit 30";
		$all = nl_db_get_all($sql,$db);
		if(is_array($all)) {
			foreach($all as $item0){
				self::execute_c2_again($item0['nns_id']);
			}
		}

		//Program
		//if(count($all)==0){//
		$sql = "select * from nns_mgtvbk_c2_log where nns_org_id='sihua' and   nns_task_type='Program' and (nns_notify_result='-1' and (nns_notify_result_url='' or nns_notify_content like '%Download picture failed%' or nns_notify_content like '%Entity queue is full%') or nns_result like '%[-1]soap info is full%'  ) and nns_again>=0 order by nns_again asc,nns_create_time asc  limit 30";
		$all_program = nl_db_get_all($sql,$db);
		if(is_array($all_program)) {
			foreach($all_program as $item1){
				self::execute_c2_again($item1['nns_id']);
			}
		}

			//Movie
			//if(count($all_program)==0){//
		$sql = "select * from nns_mgtvbk_c2_log where nns_org_id='sihua' and   nns_task_type='Movie' and (nns_notify_result='-1' and (nns_notify_content like '%the program in the mapping is not exist%' or nns_notify_content like '%Entity queue is full%' or nns_notify_content like '%Failed to synchronization MDN%') or nns_result like '%[-1]soap info is full%' ) and nns_again>=0 order by nns_again asc  limit 30";
		$all_movie = nl_db_get_all($sql,$db);
		if(is_array($all_movie)) {
			foreach($all_movie as $item2){
				self::execute_c2_again($item2['nns_id']);
			}
		}



		//Movie 连续剧 分集
		$sql = "select * from nns_mgtvbk_c2_log where nns_org_id='sihua' and   (nns_task_type='Movie' or nns_task_type='Series' or nns_task_type='Program') and (nns_notify_result='-1' and (nns_notify_content is null and nns_notify_result_url='') and (nns_result like '%[0]Soap Massage%') ) and nns_again>=0 order by nns_again asc  limit 30";
		$all_movie_notify = nl_db_get_all($sql,$db);
		if(is_array($all_movie_notify)){
			foreach($all_movie_notify as $item3){
				self::execute_c2_again($item3['nns_id']);
			}
		}



			//}
		//}
	}
	static public function execute_c2_again($nns_id){
		$db = nn_get_db(NL_DB_READ);
        $db_w = nn_get_db(NL_DB_WRITE);
		$sql = "select * from nns_mgtvbk_c2_log where nns_id='$nns_id'";
		$c2_info = nl_db_get_one($sql,$db);

		$log_summary = "对【".$c2_info['nns_task_name']."】执行【重发".$c2_info['nns_action']."命令】";
		log_model::log_write($log_summary);
		
		$file_path = dirname(dirname(dirname(dirname(__FILE__)))).'/data/mgtv/'.$c2_info['nns_org_id'].'/inject_xml/';

		if($c2_info['nns_action']!='DELETE'){
			/*if($c2_info['nns_task_type']=='Movie'){
				//如果片源的分集已经删除，则不再执行,并删除该指令
				$clip_task_info =clip_task_model::get_task_by_id($c2_info['nns_task_id']);
				if($clip_task_info){
					$sql = "select * from nns_mgtvbk_c2_task where nns_ref_id='".$clip_task_info['nns_video_index_id']."' and nns_type='index' and nns_action='destroy'";
					$result = nl_db_get_one($sql,$db);
					if($result){
						$sql = "delete  from nns_mgtvbk_c2_log where nns_id='".$nns_id."'";
						nl_execute_by_db($sql,$db_w);
						return;
					}
				}
			}*/
			$file_path = dirname(dirname(dirname(dirname(__FILE__)))).'/data/mgtv/'.$c2_info['nns_org_id'].'/inject_xml/';
		    $file = $file_path.$c2_info['nns_url'];
			if(!file_exists($file)){
				DEBUG && i_write_log('指令文件不存在:'.$file.'|重新执行注入:'.$c2_info['nns_task_type']);
				/*if($c2_info['nns_task_type']=='Movie' ){
						self::add_movies_by_clip_task($c2_info['nns_task_id']);
				}
				else */if($c2_info['nns_task_type']=='Series' || $c2_info['nns_task_type']=='Program' || $c2_info['nns_task_type']=='Movie'){
					$sql = "update nns_mgtvbk_c2_task set nns_status=-1 where nns_id='".$c2_info['nns_task_id']."'";
					nl_execute_by_db($sql,$db_w);
				}
				$sql = "delete  from nns_mgtvbk_c2_log where nns_id='".$nns_id."'";
				nl_execute_by_db($sql,$db_w);
				return true;
			}
		}
		$file = $file_path.$c2_info['nns_url'];//xml地址
		$xml_str = file_get_contents($file);
		//$CmdFileURL = C2_FTP.$c2_info['nns_url'];
		//$result = self::http_post_xml($nns_id,$xml_str);
		$c2_nns_result_arr = self::__gateway_run(GETEWAY_URL,null,'post',$xml_str,null);
		$result_arr = explode('|', $c2_nns_result_arr['data']);
		$c2_nns_result = '['.$result_arr[0].']';
		$sql = "update nns_mgtvbk_c2_log set nns_again=nns_again+1 ,nns_result='".'['.$c2_nns_result.']'."',nns_send_time=now(),nns_modify_time=now() where nns_id='".$nns_id."'";
		nl_execute_by_db($sql,$db_w);
		return true;
	}





	/**
	 * post 数据岛中专服务器
	 * @param xml_str  string 
	 * 
	 * 
	 */


	private function http_post_xml($c2_id,$xml_str){		
		$ret_data = array();
		$json_data = null;
		$http_code = null;
		$url = GETEWAY_URL;
		$vars = array('data'=>$xml_str,'nns_id'=>$c2_id);
		for ($i = 0; $i < 3; $i++) {
			include_once   dirname(dirname(dirname(dirname(dirname(__FILE__))))).'/np/np_http_curl.class.php';
			$http_client = new np_http_curl_class();
			$json_data = $http_client->post($url, $vars);
			$http_code = $http_client->curl_getinfo['http_code'];
			if ($http_code != 200) {
				continue;
			} else {
				break;
			}
		}
		//0：成功1：XML不符合规范2：服务器处理异常 3：其他错误
		if ($json_data && $http_code && $http_code == 200) {
		      $arr = explode('|', $json_data) ;
			return $arr[0];
		}
		return ERROR_CODE;//自定义错误码
	}
	
	
	
	
	static public function __gateway_run($url,$log=NULL,$method='get',$params=NULL,$header=NULL){
 	
	 	if ($method=='get'){
	 		$data = http_build_query($params);
	 		if (strpos('?',$url)>0){
	 			$url .='&'.$data;
	 		}else{
	 			$url .='?'.$data;
	 		}
	 	}	 	
	 	$ch = curl_init();		
		curl_setopt($ch, CURLOPT_HEADER, 0);		
		if (is_array($header)){
			curl_setopt($ch,CURLOPT_HTTPHEADER,$header);
		}
		curl_setopt($ch, CURLOPT_URL, $url);
		if ($method=='post'){
			curl_setopt($ch, CURLOPT_POST, 1);
			curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
		}
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_TIMEOUT, 10); //超时时间
		$output = curl_exec($ch);
		$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
		$reason = curl_error($ch);
		curl_close($ch);		
		$return=array(
			'data'=>$output,
			'code'=>$code,
			'reason'=>$reason
		); 
	 	return $return;
 	}



	/**
	 * 执行C2注入命令
	 * @param $c2_info array(
	 * 'c2_id'
	 * 'file_name'
	 * 'xml_content'
	 * )
	 */
	static public function execute_c2($c2_info){
		global $g_webdir;
		//
		// $c2_id = np_guid_rand();
		$c2_id = $c2_info['nns_id'];
		$sub_path = date('Y-m-d');
		$file = $c2_info['nns_url'];
		$c2_info['nns_url'] = $sub_path.'/'.$file;
		$xml_str = $c2_info['nns_content'];
		$file_path = dirname(dirname(dirname(dirname(__FILE__)))).'/data/mgtv/'.SP_ORG_ID.'/inject_xml/'.$sub_path.'/';
		if(!is_dir($file_path)) mkdir($file_path,0777,true);
		$file_path .= $file;
		file_put_contents($file_path,$xml_str);
		// $CmdFileURL = C2_FTP.$c2_info['nns_url'];
		//$result =  self::http_post_xml($xml_str);
		
		
		
		$result= self::__gateway_run(GETEWAY_URL,null,'post',$xml_str,null);
		$c2_info['nns_id'] = $c2_id;
		$result_arr = explode('|', $result['data']);
		$c2_info['nns_result'] = '['.$result_arr[0].']';
		//$c2_info['nns_result'] = 0;
		self::save_c2_log($c2_info);
		
		
		
		return true;

	}
	/**
	 * 保存C2命令日志
	 * $c2_log array(
	 * 'nns_id',
	 * 'nns_type',
	 * 'nns_org_id',
	 * 'nns_video_id',
	 * 'nns_video_type',
	 * 'nns_video_index_id',
	 * 'nns_media_id',
	 * 'nns_url',
	 * 'nns_content',
	 * 'nns_result',
	 * 'nns_desc',
	 * 'nns_create_time'
	 * )
	 */
	static public function save_c2_log($c2_log){
		$db = nn_get_db(NL_DB_WRITE);
		//$db->open();
		$c2_log['nns_type'] = 'std';
		$c2_log['nns_org_id'] = SP_ORG_ID;
		$dt = date('Y-m-d H:i:s');
		$c2_log['nns_create_time'] = $dt;
		$c2_log['nns_send_time'] = $dt;
		return nl_db_insert($db,'nns_mgtvbk_c2_log',$c2_log);
	}
	/**
	 * C2通知命令日志
	 * $c2_notify array(
	 * 'nns_id',
	 * 'nns_notify_result_url',
	 * 'nns_notify_result',
	 *
	 * )
	 */
	static public function save_c2_notify($c2_notify){
            DEBUG && i_write_log('---------save_c2_notify----------');
		$db = nn_get_db(NL_DB_WRITE);
	    //$db->open();
		//$sql = "update nns_mgtvbk_task set nns_state='$state' where nns_id='$task_id'";
		//return nl_db_update($db,'nns_mgtvbk_c2_log', $c2_notify, "nns_id='$task_id'");
		$dt = date('Y-m-d H:i:s');
		$sql = "update nns_mgtvbk_c2_log set " .
				"nns_notify_result_url='".$c2_notify['nns_notify_result_url']."' ," .
				"nns_notify_result='".$c2_notify['nns_notify_result']."', nns_notify_time='".$dt."'," .
				"nns_modify_time='".$dt."' " .
				"where nns_id='".$c2_notify['nns_id']."'";
        //i_write_log($sql);
		nl_execute_by_db($sql,$db);

		$db_r = nn_get_db(NL_DB_READ);
		$sql = "select * from nns_mgtvbk_c2_log where nns_id='".$c2_notify['nns_id']."'";
		$c2_info = nl_db_get_one($sql,$db_r);
		if($c2_info==false) return false;
		//删除EPG注入日志
		/*if(IMPROT_EPG===true){
			if($c2_info['nns_task_type']=='Series' || $c2_info['nns_task_type']=='Program'  ){
				if($c2_notify['nns_notify_result']!='-1'){
					$sql = "select * from nns_mgtvbk_c2_task where nns_id='".$c2_info['nns_task_id']."'";
					$mgtvbk_c2_task = nl_db_get_one($sql, $db_r);unset($sql);
					//$sql = "delete from nns_mgtvbk_import_epg where nns_video_id='{$mgtvbk_c2_task['nns_ref_id']}' and nns_org_id='{$mgtvbk_c2_task['nns_org_id']}' and ";
					//$sql .="nns_video_type='{$mgtvbk_c2_task['nns_type']}'";
					//nl_execute_by_db($sql,$db);unset($sql);
				}
			}
			
			
			
			
			if($c2_info['nns_task_type']=='Movie' ){
				if($c2_notify['nns_notify_result']!='-1'){
					$sql = "select * from nns_mgtvbk_c2_task where nns_id='".$c2_info['nns_task_id']."'";
					$mgtvbk_c2_task = nl_db_get_one($sql, $db_r);unset($sql);
					$sql = "delete from nns_mgtvbk_import_epg where nns_video_id='{$mgtvbk_c2_task['nns_ref_id']}' and nns_org_id='{$mgtvbk_c2_task['nns_org_id']}' and ";
					$sql .="nns_video_type='{$mgtvbk_c2_task['nns_type']}'";
					nl_execute_by_db($sql,$db);unset($sql);
				}
			}
			
			
		}*/

		if($c2_info['nns_task_type']=='Series' || $c2_info['nns_task_type']=='Program' ){
			if($c2_notify['nns_notify_result']=='-1'){
				$sql = "update nns_mgtvbk_c2_task set nns_status=-1,nns_modify_time=now() where nns_id='".$c2_info['nns_task_id']."'";//注入媒体时，再次发送；否则媒体注入没有绑定节目
			}else{
				$sql = "update nns_mgtvbk_c2_task set nns_status=0,nns_modify_time=now() where nns_id='".$c2_info['nns_task_id']."'";
			}
			nl_execute_by_db($sql,$db);
			//异步通知修改影片的注入状态
			$sql_c2_task = "select * from nns_mgtvbk_c2_task where nns_id='".$c2_info['nns_task_id']."'";
			$c2_task_info = nl_db_get_one($sql_c2_task,$db_r);unset($sql_c2_task);
			if(($c2_task_info['nns_type']=='vod' || $c2_task_info['nns_type']=='index') && ($c2_task_info['nns_action']=='add' || $c2_task_info['nns_action']=='modify')){
				if($c2_task_info['nns_type']=='vod'){
					$vod_id = $c2_task_info['nns_ref_id'];
				}elseif($c2_task_info['nns_type']=='index'){
					$vod_id = $c2_task_info['nns_src_id'];
				}
				$sql_vod_index = "select count(*) from nns_vod_index where nns_vod_id='".$vod_id."'";
				$index_num =  nl_db_get_col($sql_vod_index,$db_r);

				$sql_all_index = "select nns_all_index from nns_vod where  nns_id='".$vod_id."'";
				$nns_all_index = nl_db_get_col($sql_all_index,$db_r);
				if($nns_all_index==1){
					$update_vod_c2 = "update nns_mgtvbk_c2_task set  nns_status=0,nns_modify_time=now() where nns_type='vod' and nns_ref_id='{$vod_id}' and nns_org_id='{$c2_task_info['nns_org_id']}'";
					nl_execute_by_db($update_vod_c2,$db);
				}
				if($index_num>1){
					$sql_vod = "select count(*) from nns_mgtvbk_c2_task where nns_org_id='".$c2_task_info['nns_org_id']."' and nns_type='vod' and nns_ref_id='".$vod_id."'";
					$series_num = nl_db_get_col($sql_vod,$db_r);unset($sql_vod);
					$sql_vod = "select count(*) from nns_mgtvbk_c2_task where nns_org_id='".$c2_task_info['nns_org_id']."' and nns_type='index' and nns_src_id='".$vod_id."'";
					$vod_num = nl_db_get_col($sql_vod,$db_r);unset($sql_vod);
					$all = $series_num+$vod_num;
					$sql_vod = "select count(*) from nns_mgtvbk_c2_task where nns_status=0 and nns_org_id='".$c2_task_info['nns_org_id']."' and nns_type='vod' and nns_ref_id='".$vod_id."'";
					$series_num_finish = nl_db_get_col($sql_vod,$db_r);unset($sql_vod);
					$sql_vod = "select count(*) from nns_mgtvbk_c2_task where nns_status=0 and  nns_org_id='".$c2_task_info['nns_org_id']."' and nns_type='index' and nns_src_id='".$vod_id."'";
					$vod_num_finish = nl_db_get_col($sql_vod,$db_r);unset($sql_vod);
					$all_finish = $series_num_finish+$vod_num_finish;
					if($all==$all_finish){
						$sql_content_update = "update nns_mgtvbk_category_content set nns_status=1 where nns_video_id='".$vod_id."' and nns_org_id='".$c2_task_info['nns_org_id']."' and nns_video_type=0";
						nl_execute_by_db($sql_content_update,$db);
					}
					//计算注入成功的个数
				}elseif($index_num==1){
					$sql_vod = "select * from nns_mgtvbk_c2_task where nns_org_id='".$c2_task_info['nns_org_id']."' and nns_type='index' and nns_src_id='".$vod_id."'";
					$c2_task_info_result = nl_db_get_one($sql_vod,$db_r);unset($sql_vod);
					if($c2_task_info_result['nns_action']=='add' || $c2_task_info_result['nns_action']=='modify'){
						$content_status = nl_db_get_col("select count(*) from  nns_mgtvbk_category_content  where nns_video_id='".$vod_id."' and nns_org_id='".$c2_task_info['nns_org_id']."' and nns_video_type=0 and nns_status=1",$db_r);
						if($content_status==0){
							$sql_content_update = "update nns_mgtvbk_category_content set nns_status=1 where nns_video_id='".$vod_id."' and nns_org_id='".$c2_task_info['nns_org_id']."' and nns_video_type=0";
							nl_execute_by_db($sql_content_update,$db);
						}
					}
				}
			}
		}else if($c2_info['nns_task_type']=='Movie'){
			$sp_id = nl_db_get_one("select nns_org_id,nns_clip_task_id from  nns_mgtvbk_c2_task where nns_id='".$c2_info['nns_task_id']."'", $db_r);
			$rule = sp_model::get_sp_info($sp_id['nns_org_id']);
			$clip  = false;
			if($rule['nns_rule']=='100000'){
				$clip  = true;
			}
			//$clip = strstr(trim($rule['nns_rule']),'100000');
			if($c2_info['nns_action']=='DELETE'){
				if($c2_notify['nns_notify_result']=='-1'){
					$nns_state = clip_task_model::TASK_C_STATE_C2_DELETE_FAIL;
					$nns_desc = clip_task_model::$task_state_arr[clip_task_model::TASK_C_STATE_C2_DELETE_FAIL];
				}else{
					$nns_state = clip_task_model::TASK_C_STATE_C2_DELETE_SUCC;
					$nns_desc = clip_task_model::$task_state_arr[clip_task_model::TASK_C_STATE_C2_DELETE_SUCC];
					$sql = "update nns_mgtvbk_c2_task set nns_status=0 where nns_id='".$c2_info['nns_task_id']."'";
					nl_execute_by_db($sql,$db);
				}
			}else{
				if($c2_notify['nns_notify_result']=='-1'){
					$nns_state = clip_task_model::TASK_C_STATE_C2_FAIL;
					$nns_desc = clip_task_model::$task_state_arr[clip_task_model::TASK_C_STATE_C2_FAIL];
				}else{
					$nns_state = clip_task_model::TASK_C_STATE_C2_SUCC;
					$nns_desc = clip_task_model::$task_state_arr[clip_task_model::TASK_C_STATE_C2_SUCC];
					$sql = "update nns_mgtvbk_c2_task set nns_status=6 where nns_id='".$c2_info['nns_task_id']."'";
					nl_execute_by_db($sql,$db);
				}
			}

			if($clip===true){
			    //更改切片状态
				$dt = date('Y-m-d H:i:s');
				$set_state = array(
				'nns_state' => $nns_state,
				'nns_desc' => $nns_desc,
				'nns_modify_time'=>$dt,
				);
				clip_task_model::update_task($sp_id['nns_clip_task_id'], $set_state);
				//任务日志
				$task_log = array(
				'nns_task_id' => $sp_id['nns_clip_task_id'],
				'nns_state' => $nns_state,
				'nns_desc' => $nns_desc,
				);
				clip_task_model::add_task_log($task_log);
			}

		}
		if($c2_notify['nns_notify_result']=='-1'){
			//重试发送3次，后不再发送
			$sql = "update nns_mgtvbk_c2_log set nns_again=-1 where nns_id='".$c2_notify['nns_id']."' and nns_again>4";
			nl_execute_by_db($sql,$db);
		}
		
		
		/*
		//下载结果
		if(!empty($c2_notify['nns_notify_result_url'])){
			$url_arr = parse_url($c2_notify['nns_notify_result_url']);
			//
			$port = isset($url_arr["port"])?$url_arr["port"]:21;
			include_once NPDIR . '/np_ftp.php';
			$ftp1=new nns_ftp($url_arr['host'],$url_arr["user"],$url_arr["pass"],$port);
			$ftpcon1=$ftp1->connect();
            if (empty($ftpcon1)) {
                return FALSE;
            }
            $notify_save_path = dirname(dirname(dirname(dirname(__FILE__)))).'/data/mgtv/'.$c2_info['nns_org_id'].'/notify'.$url_arr["path"];
            $path_parts = pathinfo($notify_save_path);
             if (!is_dir($path_parts['dirname'])){
                 mkdir($path_parts['dirname'], 0777, true);
             }
            $rs = $ftp1->get(ltrim($url_arr["path"],'/'),$notify_save_path);
            if($rs==false){
            	DEBUG && i_write_log('---------下载 notify 失败----------');
            	return FALSE;
            }else{
            	//
            	$nns_notify_content = file_get_contents($notify_save_path);
            	if($nns_notify_content){
            		$sql = "update nns_mgtvbk_c2_log set nns_notify_content='".$nns_notify_content."' where nns_id='".$c2_notify['nns_id']."'";
				    nl_execute_by_db($sql,$db);
				    //如果因为图片的问题没有发送成功就再一次执行这个命令
					if(strpos($nns_notify_content,"ELEMENTTYPE=Picture")!==false){
						$sql="select * from nns_mgtvbk_c2_log where nns_id='".$c2_notify['nns_id']."'";
						$c2_info_picture = nl_db_get_one($sql,$db_r);
						if($c2_info_picture['nns_task_type']=='Series' || $c2_info_picture['nns_task_type']=='Program' ){
							//查询任务数据
							$sql="select * from nns_mgtvbk_c2_task where nns_id='".$c2_info_picture['nns_task_id']."'";
							$c2_task = nl_db_get_one($sql,$db_r);
							//图片的下载地址和存放地址
							$root_dir = dirname(dirname(dirname(dirname(__FILE__)))).'/data/downimg';
							$dowload_img_url = "http://img.hifuntv.com/ImageServer/image_v1.5.5/";

							if($c2_task['nns_type']=='index'){
								//查询影片的基本信息图片有没有保存
								$sql="select *  from nns_vod where nns_id='{$c2_task['nns_src_id']}'";
								$vod = nl_db_get_one($sql,$db_r);
								if(!empty($vod['nns_image2'])){
									$img_save_name = str_replace('.JPG','.jpg',$vod['nns_image2']);
									$img_file = $root_dir.$img_save_name;
									if(!file_exists($img_file) || filesize($img_file)==0){
										$img = str_replace("/prev/KsImg/", "", $vod['nns_image2']);
										self::_save_img_from_url($img_file,$dowload_img_url.$img);
									}
								}
								if(!empty($vod['nns_image0'])){
									$img_save_name = str_replace('.JPG','.jpg',$vod['nns_image0']);
									$img_file = $root_dir.$img_save_name;
									if(!file_exists($img_file) || filesize($img_file)==0){
										$img = str_replace("/prev/KsImg/", "", $vod['nns_image0']);
										self::_save_img_from_url($img_file,$dowload_img_url.$img);
									}
								}
								//查询影片分集的基本信息图片有没有保存
								$sql = "select *  from nns_vod_index where nns_id='{$c2_task['nns_ref_id']}'";
								$index_item = nl_db_get_one($sql,$db_r);
								if(!empty($index_item['nns_image'])){
									$img_save_name = str_replace('.JPG','.jpg',$index_item['nns_image']);
									$img_file = $root_dir.$img_save_name;
									if(!file_exists($img_file) || filesize($img_file)==0){
										$img = str_replace("/prev/KsImg/", "", $index_item['nns_image']);
										self::_save_img_from_url($img_file,$dowload_img_url.$img);
									}
								}
							}elseif($c2_task['nns_type']=='vod'){
								//查询影片的基本信息图片有没有保存
								$sql="select *  from nns_vod where nns_id='{$c2_task['nns_ref_id']}'";
								$vod = nl_db_get_one($sql,$db_r);
								if(!empty($vod['nns_image2'])){
									$img_save_name = str_replace('.JPG','.jpg',$vod['nns_image2']);
									$img_file = $root_dir.$img_save_name;
									if(!file_exists($img_file) || filesize($img_file)==0){
										$img = str_replace("/prev/KsImg/", "", $vod['nns_image2']);
										self::_save_img_from_url($img_file,$dowload_img_url.$img);

									}
								}
								if(!empty($vod['nns_image0'])){
									$img_save_name = str_replace('.JPG','.jpg',$vod['nns_image0']);
									$img_file = $root_dir.$img_save_name;
									if(!file_exists($img_file) || filesize($img_file)==0){
										$img = str_replace("/prev/KsImg/", "", $vod['nns_image0']);
										self::_save_img_from_url($img_file,$dowload_img_url.$img);
									}
								}
							}
							$sql = "update nns_mgtvbk_c2_task set nns_status=1,nns_action='add' where  nns_id='".$c2_info_picture['nns_task_id']."'";
				    		nl_execute_by_db($sql,$db);
							content_task_model::vod($c2_info_picture['nns_task_id']);
						}
					}
            	}

            }
		}*/
		return true;
	}


	static public function _save_img_from_url($img_file,$img_url){
		$ret_data = array();
		$json_data = null;
		$http_code = null;
		for ($i = 0; $i < 3; $i++) {
			    $http_client = new np_http_curl_class();
		        $json_data = $http_client->get($img_url);
		        $http_code = $http_client->curl_getinfo['http_code'];
		        if ($http_code != 200) {
		                //i_echo('-----下载失败:'.$img_url);
		                continue;
		        } else {
		                break;
		        }
		}
		if ($json_data && $http_code && $http_code == 200) {
		      return  file_put_contents($img_file,$json_data);
		}
		return false;
	}

	static public function update_notify_content($nns_id,$nns_notify_content){
		$db = nn_get_db(NL_DB_WRITE);
		$sql = "update nns_mgtvbk_c2_log set nns_notify_content='".$nns_notify_content."' where nns_id='".$nns_id."'";
		return nl_execute_by_db($sql,$db);
	}
	static public function get_c2_log_list($sp_id,$filter=null,$start=0,$size=100){
		$db = nn_get_db(NL_DB_READ);
		//$db->open();
		$sql = "select  * from nns_mgtvbk_c2_log where nns_org_id='".$sp_id."' ";
		$sql_count = "select  count(*) from nns_mgtvbk_c2_log where nns_org_id='".$sp_id."' ";
		if($filter != null){
			$wh_arr = array();
			if(!empty($filter['nns_task_name'])){
				$wh_arr[] = " nns_task_name like '%".$filter['nns_task_name']."%'";
			}
			if(!empty($filter['nns_id'])){
				$wh_arr[] = " nns_id='".$filter['nns_id']."'";
			}
			if(!empty($filter['nns_task_type'])){
				$wh_arr[] = " nns_task_type='".$filter['nns_task_type']."'";
			}
			if(!empty($filter['nns_action'])){
				$wh_arr[] = " nns_action='".$filter['nns_action']."'";
			}

			if(!empty($filter['day_picker_start'])){
				$wh_arr[] = " nns_create_time >='".$filter['day_picker_start']."' ";
			}
			if(!empty($filter['day_picker_end'])){
				$wh_arr[] = " nns_create_time <='".$filter['day_picker_end']."' ";
			}
			if(!empty($filter['notify_time_start'])){
				$wh_arr[] = "  nns_notify_time >='".$filter['notify_time_start']."'";
			}
			if(!empty($filter['notify_time_end'])){
				$wh_arr[] = "  nns_notify_time <='".$filter['notify_time_end']."'";
			}
			if(!empty($filter['nns_state'])){
				$state = $filter['nns_state'];
				switch($state){
					case 'request_state_succ':
					$wh_arr[] = " nns_result like '[0]%'";
					break;
					case 'request_state_fail':
					$wh_arr[] = " nns_result like '[-1]%'";
					break;
					case 'notify_state_wait':
					$wh_arr[] = " nns_notify_result is null ";
					break;
					case 'notify_state_succ':
					$wh_arr[] = " nns_notify_result='0'";
					break;
					case 'notify_state_fail':
					$wh_arr[] = " nns_notify_result='-1'";
					break;
					case 'resend_fail':
					$wh_arr[] = " nns_again=-1";
					break;
				}

			}
			if(!empty($wh_arr))	$sql .= " and ".implode(" and ",$wh_arr);
			if(!empty($wh_arr))	$sql_count .= " and ".implode(" and ",$wh_arr);
		}
		$sql .= " order by nns_create_time desc ";
		$sql .= " limit $start,$size";
		$data = nl_db_get_all($sql,$db);
    	$rows = nl_db_get_col($sql_count,$db);
    	return array('data'=>$data,'rows'=>$rows);
	}
	static public function delete_c2($ids=array()){
		$db = nn_get_db(NL_DB_WRITE);
		$db_r = nn_get_db(NL_DB_READ);
		$sql = "select nns_task_name from nns_mgtvbk_c2_log where ".nl_db_in($ids,'nns_id');
		$c2_info = nl_db_get_all($sql,$db_r);
		foreach ($c2_info as $value) {
			$log_summary = "对【".$value['nns_task_name']."】执行【删除命令】";
			log_model::log_write($log_summary);
		}
		$sql = "delete from nns_mgtvbk_c2_log where ".nl_db_in($ids,'nns_id');
		return nl_execute_by_db($sql,$db);
	}

}
